package com.topscore.uke.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.UserManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.topscore.uke.R;
import com.topscore.uke.entities.AchievementInfo;
import com.topscore.uke.entities.DateSelectorBean;
import com.topscore.uke.entities.UserInfo;
import com.topscore.uke.mvp.contractors.GetAchievementContractor;
import com.topscore.uke.mvp.presenters.GetAchievementPresenter;
import com.topscore.uke.ui.ToolBarCompatActivity;
import com.topscore.uke.ui.loadsir_callback.ErrorCallBack;
import com.topscore.uke.ui.loadsir_callback.LoadingCallBack;
import com.topscore.uke.utils.SnackBarUtil;
import com.topscore.uke.utils.UserInfoManager;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MyPerformanceActivity extends ToolBarCompatActivity implements GetAchievementContractor.View {

    private final int _SelectDatesRequest = 1012;

    @Bind(R.id.comments_layout)
    RelativeLayout commentsLayout;
    @Bind(R.id.filter_tv)
    TextView filterTv;
    @Bind(R.id.show_all_btn)
    TextView showAllBtn;
    @Bind(R.id.performance_content)
    ScrollView performanceContent;
    @Bind(R.id.personal_member_count_tv)
    TextView personalMemberCountTv;
    @Bind(R.id.recruit_member_count_tv)
    TextView recruitMemberCountTv;
    @Bind(R.id.gold_count_tv)
    TextView goldCountTv;
    @Bind(R.id.all_point_tv)
    TextView allPointTv;
    @Bind(R.id.comment_count_tv)
    TextView commentCountTv;
    @Bind(R.id.re_purchace_count_tv)
    TextView rePurchaceCountTv;
    @Bind(R.id.re_purchace_count_layout)
    RelativeLayout rePurchaceCountLayout;
    @Bind(R.id.re_purchace_percent_tv)
    TextView rePurchacePercentTv;
    @Bind(R.id.re_purchace_percent_layout)
    RelativeLayout rePurchacePercentLayout;

    private DateSelectorBean mDateBean;

    private final SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy年MM月dd日");

    private GetAchievementContractor.Presenter mAchievementPresenter;

    private LoadService mLoadService;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_filter, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_filter:
                Intent intent = new Intent(mContext, RangeDateSelectorActivity.class);
                intent.putExtra("select_dates", mDateBean);
                startActivityForResult(intent, _SelectDatesRequest);
                overridePendingTransition(R.anim.page_in_left, R.anim.page_out_right);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_performance);
        ButterKnife.bind(this);
        setCentralTitle("我的业绩");
        mAchievementPresenter = new GetAchievementPresenter(this);
        initViews();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == _SelectDatesRequest) {
            if (data != null) {
                mDateBean = data.getParcelableExtra("select_dates");
                String startDate = new SimpleDateFormat("yyyy-MM-dd").format(mDateBean.getStartDate());
                String endDate = new SimpleDateFormat("yyyy-MM-dd").format(mDateBean.getEndDate());
                mAchievementPresenter.getPerformance(startDate, endDate);
                setUpFilter();
            }
        }
    }

    private void setUpFilter() {
        if (mDateBean != null) {
            showAllBtn.setVisibility(View.VISIBLE);
            Date startDate = mDateBean.getStartDate();
            Date endDate = mDateBean.getEndDate();
            filterTv.setText(mDateFormat.format(startDate) + "\t" + "至" + "\t" + mDateFormat.format(endDate));
        } else {
            showAllBtn.setVisibility(View.GONE);
            filterTv.setText("全部");
        }
    }

    private void initViews() {
        mLoadService = LoadSir.getDefault().register(performanceContent, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                if (mDateBean == null) {
                    mAchievementPresenter.getPerformance();
                } else {
                    String startDate = new SimpleDateFormat("yyyy-MM-dd").format(mDateBean.getStartDate());
                    String endDate = new SimpleDateFormat("yyyy-MM-dd").format(mDateBean.getEndDate());
                    mAchievementPresenter.getPerformance(startDate, endDate);
                }
            }
        });
        commentsLayout.setOnClickListener(view -> {
            Intent intent = new Intent(mContext, CommentsListActivity.class);
            startActivity(intent);
        });
        switch (UserInfoManager.getUserInfo().getRole()) {
            case "UKE_SERVICE_CONSULTANT_ROLE":
                rePurchaceCountLayout.setVisibility(View.VISIBLE);
                break;
            case "UKE_IMAGE_CONSULTANT_ROLE":
                rePurchacePercentLayout.setVisibility(View.VISIBLE);
                break;
        }
        initData();
    }

    private void initData() {
        mAchievementPresenter.getPerformance();
    }

    @Override
    public void onLoading(String loadingMessage) {
        mLoadService.showCallback(LoadingCallBack.class);
    }

    @Override
    public void onLoadFinished() {
        mLoadService.showSuccess();
    }

    @Override
    public void onFail(int code, String errorMessage) {
        SnackBarUtil.getInstance(performanceContent).showShort(errorMessage).show();
        mLoadService.showCallback(ErrorCallBack.class);
    }

    @Override
    public void onGetPerformanceDataSuccess(AchievementInfo info) {
        personalMemberCountTv.setText(String.valueOf(info.getPersonalMemberCount()));
        recruitMemberCountTv.setText(String.valueOf(info.getRecruitMemberCount()));
        goldCountTv.setText(String.valueOf(info.getGoldCount()));
        allPointTv.setText(String.valueOf(info.getAllPoint()));
        rePurchaceCountTv.setText(String.valueOf(info.getRePurchaseCount()));
        rePurchacePercentTv.setText(new DecimalFormat("0.00%").format(info.getRePurchasePercent()));
    }
}
